package com.cincc.cinccimdemo.ui.main;

import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.adapter.SearchUserAdapter;
import com.cincc.cinccimdemo.ui.IMBaseNoToolbarActivity;
import com.cincc.cinccimdemo.widget.SearchView;
import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.table.IMContactUser;

import java.util.ArrayList;
import java.util.List;

public class SearchUserActivity extends IMBaseNoToolbarActivity {
    private static final String TAG = "SearchUserActivity";

    @Override
    protected int contentLayout() {
        return R.layout.search_record_activity;
    }

    RecyclerView recyclerView;
    SearchUserAdapter adapter;
    List<IMContactUser> list = new ArrayList<>();
    SearchView searchView;

    int pageIndex = 0;
    LinearLayout inputLinearlayout;
    LinearLayout emptyLinearlayout;

    @Override
    protected void afterViews() {
        super.afterViews();

        recyclerView = findViewById(R.id.recyclerView);
        searchView = findViewById(R.id.search_view);

        inputLinearlayout = findViewById(R.id.descLinearLayout);
        emptyLinearlayout = findViewById(R.id.emptyLinearLayout);
        TextView cancelText = findViewById(R.id.cancel);

        adapter = new SearchUserAdapter(this, list);
        recyclerView.setAdapter(adapter);
        searchView.setOnConfirmListener(this::refreshData);
        cancelText.setOnClickListener(view -> finish());
        adapter.setOnItemClickListener(this::startDetail);
    }

    private void refreshData(String data) {
        list.clear();
        pageIndex = 0;
        IMSipPhoneCtrl.getInstance().queryUser(data, pageIndex, imResponse -> {
            Log.e(TAG, "callback code: " + imResponse.getCode());
            Log.e(TAG, "callback msg: " + imResponse.getMsg());

            List<IMContactUser> result = (List<IMContactUser>) imResponse.getData();
            list.addAll(result);
            runOnUiThread(() -> {
                if (result.size() > 0) {
                    recyclerView.setVisibility(View.VISIBLE);
                    adapter.notifyDataSetChanged();
                }
                inputLinearlayout.setVisibility(View.GONE);
                emptyLinearlayout.setVisibility(result.size() == 0 ? View.VISIBLE : View.GONE);
            });
        });
    }

    private void startDetail(int index) {
        IMContactUser item = list.get(index);
        UserInfoActivity.startUserDetail(this, item.userId);
    }
}
